package cn.quantgroup.rabbitmq.pubsub;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * Created by 11 on 2016/12/15.
 */
public class ReceiveLogs {
    private static final String EXCHANGE_NAME = "logs";
    private static final String EXCHANGE_TYPE = "fanout";
    public static void main(String[] args) throws Exception{
        //创建连接工厂,设置连接地址，用户名，密码
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setUsername("admin");
        factory.setPassword("admin");
        //创建连接
        Connection connection = factory.newConnection();
        //通过连接创建信道,信道的创建和销毁代价比连接要小的多
        Channel channel = connection.createChannel();
        //声明交换机
        channel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE);
        //声明随机名称、自动删除、费持久化的临时队列.
        String queue = channel.queueDeclare().getQueue();
        channel.queueBind(queue, EXCHANGE_NAME, "");
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println(" [x] Received '" + message + "'");
            }
        };
        channel.basicConsume(queue, true, consumer);
    }
}
